import { ElMessage } from "element-plus";

const proxyMap = {
  gateway: import.meta.env.VITE_API_URL,
  gateways: import.meta.env.VUE_APP_GATEWAYS,
};

/**
 * 通过 /gateway/xxx 等方式获取完整请求路径
 */
const geFetchtUrl = function (url) {
  if (url.startsWith("/")) {
    Object.keys(proxyMap).forEach((key) => {
      let domain = url.split("/")[1]; // 当前服务域名
      if (domain === key) {
        url = url.replace(`/${key}/`, proxyMap[key]);
      }
    });
  }
  return url;
};

/**
 * 网络请求基础库
 */
const fetchData = function (url, method, data, extra) {
  url = geFetchtUrl(url);
  const xtoken = localStorage.getItem("xtoken");
  return new Promise((resolve, reject) => {
    fetch(url, {
      method: method, // 指定请求方法为POST
      headers: {
        xtoken,
        token: "openApi",
        "Content-Type": "application/json; charset=utf-8", // 告诉服务器发送的是JSON格式的数据
        ...extra.headers,
      },
      body: method == "get" ? null : JSON.stringify(data), // 将数据转换为JSON字符串
    })
      .then((response) => {
        // 检查响应是否成功
        if (!response.ok) {
          ElMessage.error("系统异常，请稍后再试");
        }
        return response.json(); // 解析JSON格式的响应体
      })
      .then((res) => {
        const { code, errCode, data, message, retdata } = res;
        if (code == 0 || errCode == 0) {
          if (code == 0) {
            resolve(data);
          } else if (errCode == 0) {
            resolve(retdata);
          }
        } else {
          reject(res);
          ElMessage.error(message);
        }
      })
      .catch((error) => {
        console.log("请求异常", error);
        ElMessage.error("网络异常");
      });
  });
};

/**
 * get 请求封装
 */
const fetchGet = function (url, data, extra = {}) {
  return fetchData(url, "get", data, extra);
};
/**
 * post 请求封装
 */
const fetchPost = function (url, data, extra = {}) {
  return fetchData(url, "post", data, extra);
};

export default {
  get: fetchGet,
  post: fetchPost,
};
